<script setup>
import {ref, onMounted, watch} from 'vue'
import request from '@/utils/request'
import {Goods} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'

// 商品数据 - 存储从后端获取的商品列表
const goodsList = ref([])
// 加载状态 - 控制加载动画的显示
const loading = ref(false)

// 搜索条件
const searchForm = ref({
  goodsName: '',           // 商品名称
  minGoodsPrice: null,     // 最低价格
  maxGoodsPrice: null,     // 最高价格
  goodsState: '',          // 商品状态
  goodsTypeName: '电子类',       // 商品类型
  userName: '',            // 卖家名称
  goodsUptime: []          // 上架时间范围
})

// 分页数据
const pagination = ref({
  current: 1,              // 当前页码
  size: 12,                // 每页显示数量
  total: 0                 // 总商品数量
})

// 排序条件
const sortOptions = ref({
  sortBy: '',              // 排序字段
  sortOrder: ''            // 排序顺序(asc/desc)
})

// 商品状态选项 - 下拉框中的商品状态选项
const goodsStateOptions = [
  {label: '在售', value: '在售'},
  {label: '待售', value: '待售'},
  {label: '已售罄', value: '已售罄'},
  {label: '已下架', value: '已下架'},
  {label: '未知', value: '未知'}
]

// 商品类型选项 - 下拉框中的商品类型选项
const goodsTypeOptions = [
  {label: '全部', value: ''},
  {label: '日用类', value: '日用类'},
  {label: '食品类', value: '食品类'},
  {label: '电子类', value: '电子类'},
  {label: '服饰类', value: '服饰类'},
  {label: '美妆类', value: '美妆类'},
  {label: '其他类', value: '其他类'}
]

// 获取商品列表 - 从后端获取商品数据
const fetchGoodsList = async () => {
  loading.value = true  // 开启加载状态
  try {
    // 构造请求参数
    const params = {
      ...searchForm.value,
      current: pagination.value.current,
      size: pagination.value.size,
      ...sortOptions.value
    }

    // 处理时间范围参数 - 将日期范围转换为完整的日期时间字符串
    if (params.goodsUptime && params.goodsUptime.length === 2) {
      params.goodsUptimeStart = params.goodsUptime[0] + ' 00:00:00'
      params.goodsUptimeEnd = params.goodsUptime[1] + ' 23:59:59'
    }
    delete params.goodsUptime  // 删除原始的日期范围字段

    // 过滤掉空值参数 - 避免向后端发送无意义的空参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    // 发送请求获取商品列表
    const response = await request.post('/goods/page', params)

    // 根据后端返回格式处理数据
    if (response.data) {
      // 假设后端返回格式为 { records: [...], total: 100 }
      goodsList.value = response.data.records || response.data.data || response.data
      pagination.value.total = response.data.total || response.data.length || 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false  // 关闭加载状态
  }
}

// 搜索商品 - 触发搜索并重置到第一页
const handleSearch = () => {
  pagination.value.current = 1
  fetchGoodsList()
}

// 重置搜索 - 清空所有搜索条件并重新加载数据
const resetSearch = () => {
  searchForm.value = {
    goodsName: '',
    minGoodsPrice: null,
    maxGoodsPrice: null,
    goodsState: '',
    goodsTypeName: '电子类',
    userName: '',
    goodsUptime: []
  }
  sortOptions.value = {
    sortBy: '',
    sortOrder: ''
  }
  pagination.value.current = 1
  fetchGoodsList()
}

// 处理分页变化 - 当用户切换页码时调用
const handlePageChange = (page) => {
  pagination.value.current = page
  fetchGoodsList()
}

// 处理每页大小变化 - 当用户更改每页显示数量时调用
const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.current = 1
  fetchGoodsList()
}

// 处理排序变化 - 当用户选择不同的排序方式时调用
const handleSortChange = (command) => {
  // 修复排序命令处理
  if (typeof command === 'string') {
    sortOptions.value = JSON.parse(command)
  } else {
    sortOptions.value = {...command}
  }
  pagination.value.current = 1
  fetchGoodsList()
}

// 获取用户收藏列表 - 从后端获取当前用户的收藏商品列表
const getUserFavorites = async () => {
  try {
    const response = await request.post('/favorites/get', {})
    return response.data || []
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    return []
  }
}

// 检查商品是否已收藏 - 判断指定商品是否已在用户的收藏列表中
const isFavorite = async (goodsId) => {
  try {
    const favorites = await getUserFavorites()
    // 使用some方法检查是否有匹配的商品ID
    return favorites.some(fav => fav.goodsId === goodsId)
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return false
  }
}

// 添加收藏功能 - 将商品添加到用户的收藏列表
const addToFavorites = async (goodsId) => {
  try {
    // 先检查是否已收藏，避免重复添加
    const alreadyFavorited = await isFavorite(goodsId)
    if (alreadyFavorited) {
      ElMessage.warning('该商品已在收藏夹中')
      return
    }

    // 如果未收藏，则添加收藏
    await request.post('/favorites/add', {goodsId})
    ElMessage.success('商品已添加到收藏夹')
  } catch (error) {
    console.error('添加收藏失败:', error)
    ElMessage.error('添加收藏失败')
  }
}

// 监听商品类型和商品状态的变化，自动触发搜索
// 当商品类型改变时自动搜索
watch(() => searchForm.value.goodsTypeName, (newVal, oldVal) => {
  // 避免初始化时触发搜索
  if (oldVal !== undefined) {
    handleSearch()
  }
})

// 当商品状态改变时自动搜索
watch(() => searchForm.value.goodsState, (newVal, oldVal) => {
  // 避免初始化时触发搜索
  if (oldVal !== undefined) {
    handleSearch()
  }
})

// 组件挂载时获取商品列表
onMounted(() => {
  fetchGoodsList()
})
</script>

<template>
  <div class="commodity-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" label-width="100px" class="search-form">
          <!-- 第一行搜索条件：商品名称、商品状态、价格区间 -->
          <el-row :gutter="20">
            <!-- 商品名称输入框 -->
            <el-col :span="8">
              <el-form-item label="商品名称">
                <el-input
                    v-model="searchForm.goodsName"
                    placeholder="请输入商品名称"
                    clearable
                />
              </el-form-item>
            </el-col>

            <!-- 商品状态下拉选择 -->
            <el-col :span="8">
              <el-form-item label="商品状态">
                <el-select
                    v-model="searchForm.goodsState"
                    placeholder="请选择状态"
                    clearable
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in goodsStateOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 价格区间输入 -->
            <el-col :span="8">
              <div class="price-range">
                <el-form-item label="价格区间">
                  <div class="price-inputs">
                    <el-input
                        v-model.number="searchForm.minGoodsPrice"
                        placeholder="最低价"
                        type="number"
                        class="price-input"
                    />
                    <span class="separator">-</span>
                    <el-input
                        v-model.number="searchForm.maxGoodsPrice"
                        placeholder="最高价"
                        type="number"
                        class="price-input"
                    />
                  </div>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <!-- 第二行搜索条件：商品类型、卖家名称、上架时间 -->
          <el-row :gutter="20">
            <!-- 商品类型下拉选择 -->
            <el-col :span="8">
              <el-form-item label="商品类型">
                <el-select
                    v-model="searchForm.goodsTypeName"
                    placeholder="请选择商品类型"
                    clearable
                    style="width: 100%"
                >
                  <el-option
                      v-for="item in goodsTypeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 卖家名称输入框 -->
            <el-col :span="8">
              <el-form-item label="卖家名称">
                <el-input
                    v-model="searchForm.userName"
                    placeholder="请输入卖家名称"
                    clearable
                />
              </el-form-item>
            </el-col>

            <!-- 上架时间日期选择器 -->
            <el-col :span="8">
              <el-form-item label="上架时间">
                <el-date-picker
                    v-model="searchForm.goodsUptime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 操作按钮区域 -->
          <el-row :gutter="20" justify="end">
            <el-col :span="24" class="button-group">
              <!-- 排序方式下拉菜单 -->
              <el-dropdown @command="handleSortChange">
                <el-button>
                  排序方式<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="JSON.stringify({ sortBy: 'goodsPrice', sortOrder: 'asc' })">
                      价格从低到高
                    </el-dropdown-item>
                    <el-dropdown-item :command="JSON.stringify({ sortBy: 'goodsPrice', sortOrder: 'desc' })">
                      价格从高到低
                    </el-dropdown-item>
                    <el-dropdown-item :command="JSON.stringify({ sortBy: 'goodsUptime', sortOrder: 'asc' })">
                      上架时间从早到晚
                    </el-dropdown-item>
                    <el-dropdown-item :command="JSON.stringify({ sortBy: 'goodsUptime', sortOrder: 'desc' })">
                      上架时间从晚到早
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <!-- 搜索按钮 -->
              <el-button type="primary" @click="handleSearch">搜索</el-button>

              <!-- 重置按钮 -->
              <el-button @click="resetSearch">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>

    <!-- 商品列表 -->
    <div class="goods-list">
      <!-- 骨架屏加载效果 -->
      <el-skeleton :loading="loading" animated :count="4">
        <!-- 加载状态下的骨架屏模板 -->
        <template #template>
          <el-row :gutter="20">
            <el-col
                v-for="n in 8"
                :key="n"
                :span="6"
                style="margin-bottom: 20px"
            >
              <el-card class="goods-card-skeleton">
                <el-skeleton-item variant="image" style="width: 100%; height: 200px"/>
                <div style="padding: 14px">
                  <el-skeleton-item variant="h3" style="width: 50%"/>
                  <div>
                    <el-skeleton-item variant="text" style="margin-right: 16px"/>
                    <el-skeleton-item variant="text" style="width: 30%"/>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </template>

        <!-- 商品列表内容 -->
        <template #default>
          <el-row :gutter="20">
            <el-col
                v-for="item in goodsList"
                :key="item.goodsId"
                :span="6"
                style="margin-bottom: 20px"
            >
              <el-card class="goods-card" shadow="hover">
                <!-- 商品图片占位 -->
                <div class="goods-image">
                  <el-image
                      :src="item.goodsImageUrl"
                      class="image"
                      fit="cover"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon>
                          <Goods/>
                        </el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>

                <!-- 商品信息展示 -->
                <div class="goods-info">
                  <div class="goods-name">{{ item.goodsName }}</div>
                  <div class="goods-price">¥{{ item.goodsPrice }}</div>
                  <div class="goods-quantity">库存: {{ item.goodsQuantity }}</div>
                  <div class="goods-type">类型: {{ item.goodsTypeName }}</div>
                  <div class="goods-seller">卖家: {{ item.userName }}</div>
                  <div class="goods-state">
                    <el-tag
                        :type="item.goodsState === '在售' ? 'success' :
                           item.goodsState === '已售罄' ? 'info' : 'warning'"
                    >
                      {{ item.goodsState }}
                    </el-tag>
                  </div>
                  <div class="goods-time">
                    上架时间: {{ item.goodsUptime ? new Date(item.goodsUptime).toLocaleString() : '' }}
                  </div>
                </div>

                <!-- 商品操作按钮 -->
                <div class="goods-actions">
                  <!-- 添加收藏按钮 -->
                  <el-button type="primary" size="small" plain @click="addToFavorites(item.goodsId)">添加收藏
                  </el-button>
                  <!-- 加入购物车按钮 -->
                  <el-button type="success" size="small">加入购物车</el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
                v-model:current-page="pagination.current"
                v-model:page-size="pagination.size"
                :page-sizes="[10, 12, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            />
          </div>
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<style scoped>
/* 容器样式 */
.commodity-container {
  padding: 20px;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
}

.search-form {
  width: 100%;
}

/* 价格区间样式 */
.price-range {
  display: flex;
  align-items: center;
}

.price-inputs {
  display: flex;
  align-items: center;
  width: 100%;
}

.price-input {
  flex: 1;
}

.separator {
  margin: 0 10px;
  font-weight: bold;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 商品列表样式 */
.goods-list {
  min-height: 500px;
}

.goods-card {
  border-radius: 8px;
  transition: transform 0.3s ease;
}

.goods-card:hover {
  transform: translateY(-5px);
}

/* 商品图片样式 */
.goods-image {
  height: 200px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 15px;
}

.image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

/* 商品信息样式 */
.goods-info {
  margin-bottom: 15px;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.goods-price {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 5px;
}

.goods-quantity {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.goods-type, .goods-seller {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.goods-state {
  margin-bottom: 5px;
}

.goods-time {
  font-size: 12px;
  color: #999;
}

/* 商品操作按钮样式 */
.goods-actions {
  display: flex;
  justify-content: space-between;
}

/* 分页组件样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.goods-card-skeleton {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .el-col {
    flex: 0 0 100%;
    max-width: 100%;
  }

  .button-group {
    justify-content: center;
    margin-top: 15px;
  }
}
</style>
